package com.ywgt.system.controller;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywgt.handler.BusinessException;
import com.ywgt.response.Result;
import com.ywgt.response.ResultCode;
import com.ywgt.system.pojo.*;
import com.ywgt.system.service.*;
import com.ywgt.system.vo.RoleTransferItemVO;
import com.ywgt.system.vo.UserInfoVO;
import com.ywgt.system.vo.UserVO;
import com.ywgt.utils.WriteJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@RestController
@RequestMapping("/system/user")
@Api(value = "用户管理", tags = "用户模块")
//@CrossOrigin
public class UserController extends WriteJson {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserRoleService userRoleService;

    @ApiOperation(value = "查询用户信息",notes ="根据条件查询用户" )
    @GetMapping("/findUserList")
    public Result findUserList(@RequestParam(value = "pageNum",defaultValue = "1",required = false)Long pageNum,
                               @RequestParam(value = "pageSize",defaultValue = "5",required = false)Long pageSize,
                               UserVO userVO){
        Page<User> userPage=userService.findUserList(pageNum,pageSize,userVO);
        List<User> records = userPage.getRecords();
        long total = userPage.getTotal();
        return Result.ok().data("rows",records).data("total",total);
    }


    @GetMapping("/info")
    @ApiOperation(value = "用户详情",notes = "用户页面展示")
    public Result info(HttpServletResponse response, HttpServletRequest request){
        AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.getUserByUsername(authUser.getUsername());
        user.setPassword(null);
        UserInfoVO userInfoVO=new UserInfoVO();
        userInfoVO.setAvatar(user.getAvatar());
        userInfoVO.setDepartment(departmentService.getById(user.getDepartmentId()).getName());
        List<Menu> menus = menuService.getMenuByUsername(user.getUsername());
        Set<String> urls=new HashSet<>();
        for (Menu menu : menus) {
           urls.add(menu.getUrl());
        }
        userInfoVO.setUrl(urls);
        userInfoVO.setNickname(user.getNickname());
        List<String> roles = roleService.getRolesByUserName(user.getUsername());
        userInfoVO.setRoles(roles);
        List<Role> roleList = roleService.getRoles(user.getId());
        Set<String> perms=new HashSet<>();
        for (Role role : roleList) {
            perms.add(role.getRemark());
        }
        userInfoVO.setPerms(perms);
        userInfoVO.setIsAdmin(false);
        for (Role role : roleList) {
            if (role.getId()==125){
                userInfoVO.setIsAdmin(true);
                break;
            }
        }
        userInfoVO.setUsername(user.getUsername());
        return Result.ok().data("userInfo",userInfoVO);
    }

    @GetMapping("/findMenu")
    @ApiOperation(value = "菜单列表",notes = "用户菜单列表")
    public Result menu(){
        System.out.println("调用menu");
        AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Menu> menuList = menuService.getMenuByUsername(authUser.getUsername());
        return Result.ok().data("menuList",menuList);
    }
    @PostMapping("/add")
    @ApiOperation(value = "注册",notes = "用户注册")
    public Result register(@RequestBody User user){
        if (!StringUtils.isEmpty(user)){
            userService.addUser(user);
            return Result.ok();
        }
        return Result.error().code(ResultCode.PARAM_NOT_COMPLETE.getResultCode()).message(ResultCode.PARAM_NOT_COMPLETE.getResultMessage());
    }


    @GetMapping("/edit/{id}")
    @ApiOperation(value = "用户个人信息" ,notes = "查询单个用户")
    public Result getUserById(@PathVariable Long id){
        User user = userService.getById(id);
        if (user==null){
            throw new BusinessException(ResultCode.ERROR.getResultCode(),"用户不存在");
        }else {
            user.setPassword(null);
            return Result.ok().code(ResultCode.SUCCESS.getResultCode()).message(ResultCode.SUCCESS.getResultMessage()).data("user",user);
        }
    }

//    @GetMapping
//    @ApiOperation(value = "用户列表" ,notes = "根据条件查询用户")
//    public Result getUserPage(@RequestParam(required = true,defaultValue ="1")Long current, @RequestParam(required =true, defaultValue = "6") Long size
//    ,@RequestBody UserVO userVO) {
//            Page<User> page=new Page(current,size);
//            QueryWrapper<User> wrapper=createWrapper(userVO);
//            IPage<User> userPage = userService.findUserPage(page, wrapper);
//            List<User> records = userPage.getRecords();
//            if (records!=null&&records.size()>0) {
//                long total = userPage.getTotal();
//                return Result.ok().data("records", records).data("total", total);
//            }else {
//                return Result.error().code(ResultCode.USER_NOT_EXIST.getResultCode()).message(ResultCode.USER_NOT_EXIST.getResultMessage());
//            }
//        }


//    @GetMapping("/findUserList")
//    @ApiOperation(value = "用户列表" ,notes = "根据条件查询用户")
//    public Result getUsers(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,@RequestParam(value = "pageSize",defaultValue = "6")Integer pageSize,
//                           UserVO userVO) {
//        Page<User> page=new Page<>(pageNum,pageSize);
//        QueryWrapper<User> queryWrapper = createWrapper(userVO);
//        Page<User> userPage = userService.page(page, queryWrapper);
//        List<User> records = userPage.getRecords();
//        long total = userPage.getTotal();
//        return  Result.ok().data("row",records).data("total",total);
//    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除用户",notes = "根据id删除用户")
    public Result deleteUser(@PathVariable("id") Long id){
        if (StringUtils.isEmpty(id)){
          throw new BusinessException(ResultCode.PARAM_IS_BLANK.getResultCode(),ResultCode.PARAM_IS_BLANK.getResultMessage());
        }
        boolean flag = userService.removeById(id);
        if (flag){
            return Result.ok();
        }else {
            return Result.error().code(ResultCode.USER_NOT_EXIST.getResultCode()).message(ResultCode.USER_NOT_EXIST.getResultMessage());
        }
    }

    @PutMapping("/updateStatus/{id}/{status}")
    @ApiOperation(value = "更改状态",notes = "修改用户状态")
    public Result updateStatus(@PathVariable("id") Long id,@PathVariable("status") Integer status){
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ResultCode.PARAM_IS_BLANK.getResultCode(),ResultCode.PARAM_IS_BLANK.getResultMessage());
        }
        LambdaUpdateWrapper<User> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId,id);
        updateWrapper.set(User::getStatus,(status==0)?1:0);
        System.out.println(status);
        boolean flag = userService.update(updateWrapper);
        if (flag){
            return Result.ok();
        }else {
            return Result.error().code(ResultCode.USER_NOT_EXIST.getResultCode()).message(ResultCode.USER_NOT_EXIST.getResultMessage());
        }
    }


    @PutMapping("/update/{id}")
    @ApiOperation(value = "更改信息",notes = "修改用户信息")
    public Result updateUser(@PathVariable("id")Long id,@RequestBody User user){
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ResultCode.PARAM_IS_BLANK.getResultCode(),ResultCode.PARAM_IS_BLANK.getResultMessage());
        }
        int count = userService.updateUser(user);
        if (count==1){
            return Result.ok();
        }else {
            return Result.error().code(ResultCode.USER_NOT_EXIST.getResultCode()).message(ResultCode.USER_NOT_EXIST.getResultMessage());
        }
    }

    @GetMapping("/{id}/roles")
    @ApiOperation(value = "查询所有角色及用户拥有角色",notes = "查询角色")
    public Result getRoles(@PathVariable("id")Long id){
        List<Role> roleList = roleService.list();
        List<Role> roles = roleService.getRoles(id);
        List<Long> ids=new ArrayList<>();
        for (Role role : roles) {
            ids.add(role.getId());
        }
        List<RoleTransferItemVO> roleTransferItemVOS=new ArrayList<>();
        for (Role role : roleList) {
            RoleTransferItemVO roleTransferItemVO=new RoleTransferItemVO();
            roleTransferItemVO.setKey(role.getId());
            roleTransferItemVO.setLabel(role.getRoleName());
            roleTransferItemVO.setDisabled(role.getStatus()==0);
            roleTransferItemVOS.add(roleTransferItemVO);
        }
        return Result.ok().data("roles",roleTransferItemVOS).data("value",ids);
    }

    @ApiOperation(value = "添加用户角色",notes = "添加用户角色")
    @PostMapping("/{id}/assignRoles")
    public Result addRolesForUser(@PathVariable("id") Long id,@RequestBody Long[] value){
        if (value.length>0) {
            Collection<UserRole> collection = new ArrayList<>();
            for (int i = 0; i < value.length; i++) {
                UserRole userRole = new UserRole();
                userRole.setUserId(id);
                userRole.setRoleId(value[i]);
                collection.add(userRole);
            }
            if (userRoleService.saveBatch(collection)) {
                return Result.ok();
            }
        }
        return Result.error();
    }


}




